// 用户模块
import { login } from '@/api/user'
import { getToken, setToken, removeToken, setTime, getUser, setUser, removeUser } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes } from '@/router'

const state = {
  token: getToken(), // 存储用户token, 一进来先从cookie中取
  userInfo: getUser(), // 用户信息
  power: '',
  routes: [...constantRoutes, ...asyncRoutes]
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTime(Date.now())
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
    setUser(payload)
  },
  setPower(state, payload) {
    state.power = payload
  },
  removePower(state) {
    state.power = ''
  },
  removeUserInfo(state) {
    state.userInfo = {}
    state.power = ''
    removeUser()
  },
  setRoutes(state, otherRoutes) {
    state.routes = [...constantRoutes, ...asyncRoutes, ...otherRoutes]
  }
}

const actions = {
  // 登录
  async login({ commit }, payload) {
    const res = await login(payload)
    commit('setUserInfo', { ...res })
  },
  async getUserInfo({ commit }) {
    // const res = await getUserInfo()
    // const res2 = await getUserDetail(res.userId)
    // commit('setUserInfo', { ...res })
  },
  async getPower({ commit }, payload) {
    commit('setPower', payload)
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
    commit('removePower')
    commit('setRoutes', [])
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

